<template>
  <div class="hp100">
    <DataOverview class="h220" />
    <div class="echarts_parent flb mt15 h330 wp100">
      <div class="echarts wp50">
        <div class="flex_space_between echarts_header">
          <span>回款金额</span>
          <div class="flr">
            <el-select v-model="saleTrendType" size="small" class="pub_select pub_select1 mr16" @change="type => filterDimension(type, 'saleTrendDateRange')">
              <el-option v-for="item in $staticData.timeDimension" :key="item.key" :label="item.label" :value="item.key"> </el-option>
            </el-select>
            <el-date-picker v-if="saleTrendType === '1'" v-model="saleTrendDateRange" :picker-options="pickerOptions" size="small" unlink-panels type="daterange" class="pub_date_picker" :clearable="false" @change="time => changeSaleTrend(time, '1')" />
            <el-date-picker v-else-if="saleTrendType === '2'" v-model="saleTrendDateRange" :picker-options="pickerOptions1" size="small" unlink-panels type="monthrange" class="pub_date_picker" :clearable="false" @change="time => changeSaleTrend(time, '2')" />
            <el-date-picker v-else-if="saleTrendType === '3'" v-model="saleTrendDateRange" :picker-options="pickerOptions2" size="small" unlink-panels type="monthrange" class="pub_date_picker" :clearable="false" @change="time => changeSaleTrend(time, '2')" />
          </div>
        </div>
        <ContentCountAnalysis v-show="saleTrendDataHasZero == false" ref="contentCountAnalysisRef" class="hc32 wp100" :echarts-data="saleTrendData" />
        <PageEmptyData v-if="saleTrendDataHasZero == true" :text="'暂无数据'" />
      </div>
      <div class="echarts wp50">
        <div class="flex_space_between echarts_header">
          <span>回款订单</span>
          <div class="flr">
            <el-select v-model="saleCountTrendType" size="small" class="pub_select pub_select1 mr16" @change="type => filterDimension(type, 'saleTrendDateRange')">
              <el-option v-for="item in $staticData.timeDimension" :key="item.key" :label="item.label" :value="item.key"> </el-option>
            </el-select>
            <el-date-picker v-if="saleCountTrendType === '1'" v-model="salesCountTrendDateRange" :picker-options="pickerOptions" size="small" unlink-panels type="daterange" class="pub_date_picker" :clearable="false" @change="time => changeSalesCountTrend(time, '1')" />
            <el-date-picker v-else-if="saleCountTrendType === '2'" v-model="salesCountTrendDateRange" :picker-options="pickerOptions1" size="small" unlink-panels type="monthrange" class="pub_date_picker" :clearable="false" @change="time => changeSalesCountTrend(time, '2')" />
            <el-date-picker v-else-if="saleCountTrendType === '3'" v-model="salesCountTrendDateRange" :picker-options="pickerOptions2" size="small" unlink-panels type="monthrange" class="pub_date_picker" :clearable="false" @change="time => changeSalesCountTrend(time, '2')" />
          </div>
        </div>
        <SaleTrend v-show="salesCountTrendDataHasZero == false" ref="saleTrendRef" class="hc32 wp100" :echarts-data="salesCountTrendData" />
        <PageEmptyData v-if="salesCountTrendDataHasZero == true" :text="'暂无数据'" />
      </div>
    </div>
    <div class="bWH mt15 wp100 p16 br20 tableBox">
      <!-- ====== 表格上方的筛选条件 start ======-->
      <div class="table_filter flex_space_between h32">
        <div class="flex_start ">
          <div class="table_filter_search">
            <el-input v-model="orderParams.commonSearch" class="pub_input pub_input_search" placeholder="搜索" clearable @keydown.enter.native="filterCommit" @clear="filterCommit">
              <img slot="prefix" src="@/assets/img/orderManagement/search.png" class="pub_imgSize16" />
            </el-input>
          </div>
          <div class="ml8">
            <el-button type="text" class="high_filter_btn pub_button" :class="isShowFilter ? 'pub_buttonGreen' : ''" @click="isShowFilter = !isShowFilter">
              <img v-if="!isShowFilter" src="@/assets/img/orderManagement/high_filter.png" alt="高级筛选" />
              <img v-else src="@/assets/img/orderManagement/high_filterFFF.png" alt="高级筛选" />
              <span class="ml5">高级筛选</span>
            </el-button>
          </div>
          <div v-if="!isShowFilter" class="ml8">
            <el-button type="text" class="public_confirm_btn pub_button" @click="filterCommit"> 搜索 </el-button>
          </div>
        </div>
        <div class="flex_start flex_end">
          <div class="ml12">
            <el-button type="text" class="w148 pub_button" @click="markInvoiceNo('addDialogVisible')">
              <img src="@/assets/img/orderManagement/addTicket.png" alt="标记发票号" />
              <span class="ml5">标记发票号</span>
            </el-button>
          </div>
          <div class="ml12">
            <el-button type="text" class="w128 pub_button" @click="batchUpdateBtn('addReceiveDialogVisible')">
              <img src="@/assets/img/orderManagement/return.png" alt="标记回款" />
              <span class="ml5">标记回款</span>
            </el-button>
          </div>
          <div class="ml12">
            <el-button type="text" class="w148 pub_button" @click="batchUpdateBtn('addInputTicketDialogVisible')">
              <img src="@/assets/img/orderManagement/inputTicket.png" alt="标记进项票" />
              <span class="ml5">标记进项票</span>
            </el-button>
          </div>
          <div class="ml12">
            <el-button type="text" class="w128 pub_button" @click="exportListBtn('exportOrderBtnClick')">
              <img src="@/assets/img/orderManagement/export.png" alt="导出订单" />
              <span class="ml5">导出订单</span>
            </el-button>
          </div>
          <div class="ml12">
            <el-button type="text" class="w148 pub_button" @click="exportListBtn('exportOutOrderBtnClick')">
              <img src="@/assets/img/orderManagement/export.png" alt="导出出库单" />
              <span class="ml5">导出出库单</span>
            </el-button>
          </div>
          <div class="ml12">
            <el-button type="text" class="w148 pub_button" @click="exportListBtn('exportInvoiceBtnClick')">
              <img src="@/assets/img/orderManagement/export.png" alt="导出开票单" />
              <span class="ml5">导出开票单</span>
            </el-button>
          </div>
        </div>
      </div>
      <div v-if="isShowFilter" class="flex_start mt10 h100">
        <el-form ref="ruleForm" label-width="5rem" class="addOrder">
          <el-form-item label="开始日期">
            <el-date-picker v-model="orderParams.startTime" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" class="pub_date_picker" />
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker v-model="orderParams.endTime" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" class="pub_date_picker" />
          </el-form-item>
          <el-form-item label="销售">
            <el-input v-model="orderParams.companySaleName" placeholder="搜索销售" class="pub_input" />
          </el-form-item>
          <el-form-item label="采购人">
            <el-input v-model="orderParams.customerPurchaserName" placeholder="搜索采购人" class="pub_input" />
          </el-form-item>
          <el-form-item label="品牌">
            <el-input v-model="orderParams.productBrandName" placeholder="搜索品牌" class="pub_input" />
          </el-form-item>
          <el-form-item label="货号">
            <el-input v-model="orderParams.productBrandArticleNo" placeholder="搜索货号" class="pub_input" />
          </el-form-item>
          <el-form-item label="产品名称">
            <el-input v-model="orderParams.productBrandArticleNoName" placeholder="搜索采产品名称" class="pub_input" :maxlength="500" />
          </el-form-item>
          <el-form-item label="供应商">
            <el-input v-model="orderParams.productBrandArticleNo" placeholder="搜索供应商" class="pub_input" />
          </el-form-item>
          <el-form-item label="出货数量">
            <el-input v-model="orderParams.qty" placeholder="输入数量" class="pub_input" />
          </el-form-item>
          <el-form-item class="search_btn" label-width="1.25rem">
            <el-button type="text" class="public_confirm_btn pub_button" @click="filterCommit"> 搜索 </el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- ====== 表格上方的筛选条件 end ======-->
      <el-table ref="multipleTable" size="mini" border :data="tableData" tooltip-effect="dark" :class="[isShowFilter ? '' : 'mt12']" :height="`${536 * $f}px`" @selection-change="handleSelectionChange">
        <el-table-column type="selection" :width="`${50 * $f}`" align="center" fixed="left" />
        <el-table-column prop="id" label="订单号" show-overflow-tooltip :min-width="`${170 * $f}`" align="center" />
        <el-table-column prop="dateInput" label="订单日期" show-overflow-tooltip :min-width="`${100 * $f}`" align="center" />
        <el-table-column prop="companyName" label="公司名称" show-overflow-tooltip :min-width="`${200 * $f}`" align="center" />
        <el-table-column prop="companySaleName" label="销售" show-overflow-tooltip :min-width="`${120 * $f}`" align="center" />
        <el-table-column prop="invoiceNo" label="发票号" show-overflow-tooltip :min-width="`${170 * $f}`" align="center">
          <template slot-scope="{ row }">
            {{ row.invoiceNo || '/' }}
          </template>
        </el-table-column>
        <el-table-column prop="purchaseTotalPrice" label="是否回款" show-overflow-tooltip :min-width="`${80 * $f}`" align="center">
          <template slot-scope="{ row }">
            <div v-if="row.purchaseInvoiceReceive === '1'" class="cGR">已回款</div>
            <div v-else class="cRD">未回款</div>
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户名称" show-overflow-tooltip :min-width="`${120 * $f}`" align="center" />
        <el-table-column prop="customerPurchaserName" label="采购人" :min-width="`${100 * $f}`" align="center" />
        <el-table-column prop="productBrandName" label="品牌" show-overflow-tooltip :min-width="`${120 * $f}`" align="center" />
        <el-table-column prop="productBrandArticleNo" label="货号" show-overflow-tooltip :min-width="`${150 * $f}`" align="center" />
        <el-table-column prop="productBrandArticleNoName" label="产品名称" show-overflow-tooltip :min-width="`${200 * $f}`" align="center" />
        <el-table-column prop="productSpecificationName" label="规格" show-overflow-tooltip :min-width="`${250 * $f}`" align="center" />
        <el-table-column prop="qty" label="订单数量" show-overflow-tooltip :min-width="`${150 * $f}`" align="center">
          <template slot-scope="{ row }">
            {{ Number(row.qty) }}
          </template>
        </el-table-column>
        <el-table-column prop="customerSinglePrice" label="出货单价" show-overflow-tooltip :min-width="`${150 * $f}`" align="center" />
        <el-table-column prop="customerTotalPrice" label="出货总价" show-overflow-tooltip :min-width="`${150 * $f}`" align="center" />
        <el-table-column prop="purchaseSinglePrice" label="进货但价" show-overflow-tooltip :min-width="`${150 * $f}`" align="center" />
        <el-table-column prop="purchaseTotalPrice" label="进货总价" show-overflow-tooltip :min-width="`${150 * $f}`" align="center" />
        <el-table-column prop="productSupplierName" label="供应商" show-overflow-tooltip :min-width="`${150 * $f}`" align="center" />
        <el-table-column prop="purchaseTotalPrice" label="进项票" show-overflow-tooltip :min-width="`${100 * $f}`" align="center">
          <template slot-scope="{ row }">
            <div v-if="row.purchaseInvoice === '1'" class="cGR">已进项票</div>
            <div v-else class="cRD">未进项票</div>
          </template>
        </el-table-column>
        <template slot="empty">
          <PageEmptyData />
        </template>
      </el-table>
      <div class="pub_pageination flex_center mt10 h32">
        <el-pagination background layout="total,prev, pager, next,sizes" :page-size="orderParams.pageSize" :current-page.sync="orderParams.pageNum" :total="orderParams.total" @current-change="orderChangePage" @size-change="orderChangeSize"> </el-pagination>
      </div>
    </div>
    <!-- 导入弹窗 -->
    <PageDialog :title="'导入'" :dialog-visible="importDialogVisible" :width="`${$f * 600}px`" @close="closeDialog">
      <el-upload ref="upload" class="pub_upload" drag :data="{ file: fileList }" :action="uploadFileUrl" :on-success="uploadFileSucess" :auto-upload="false" :limit="1" :headers="headers" :file-list="fileList" :on-remove="handleRemoveFile" :on-change="changeUploadFile">
        <img src="@/assets/img/orderManagement/import.png" alt="导入" class="pub_imgSize30 mt36 mb16" />
        <div class="pub_importFile_tip">将文件拖到此处，或<em class="ml5">点击上传</em></div>
        <div class="pub_importFile_tip mt10">仅支持Word、Excel</div>
      </el-upload>
    </PageDialog>
    <!-- 导出提示 -->
    <PageDialog :title="'导入'" :dialog-visible="exporttDialogVisible" :width="`${$f * 600}px`" @close="closeDialog">
      <div class="pub_tips">
        将导出Excel表格，请确认是否导出？
      </div>
    </PageDialog>
    <!-- 编辑发票号 -->
    <PageDialog title="编辑发票号" :dialog-visible="addDialogVisible" :width="`${$f * 600}px`" @close="closeDialog" @submit="confirmTicket">
      <el-form ref="ruleForm" :model="addParams" :rules="ticketRules" label-width="4.375rem">
        <el-form-item label="发票号" prop="invoiceNo">
          <el-input v-model="addParams.invoiceNo" placeholder="请输入发票号" class="pub_input" :maxlength="20" />
        </el-form-item>
      </el-form>
    </PageDialog>
    <!-- 标记回款 -->
    <PageDialog title="标记回款" :dialog-visible="addReceiveDialogVisible" :width="`${$f * 600}px`" @close="closeDialog" @submit="confirmMark">
      <el-form ref="ruleForm" :model="addParams" :rules="receiveRules" label-width="5rem">
        <el-form-item label="是否回款" prop="purchaseInvoiceReceive">
          <el-select v-model="addParams.purchaseInvoiceReceive" placeholder="请选择" class="pub_select">
            <el-option v-for="item in purchaseInvoiceReceiveList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </PageDialog>
    <!-- 进项票 -->
    <PageDialog title="标记进项票" :dialog-visible="addInputTicketDialogVisible" :width="`${$f * 600}px`" @close="closeDialog" @submit="confirmInputTicket">
      <el-form ref="ruleForm" :model="addParams" :rules="inputTicketRules" label-width="5rem">
        <el-form-item label="进项票" prop="purchaseInvoice">
          <el-select v-model="addParams.purchaseInvoice" placeholder="请选择" class="pub_select">
            <el-option v-for="item in purchaseInvoiceList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </PageDialog>
    <!-- 出库单导出时银行信息 -->
    <PageDialog title="银行信息" :dialog-visible="showBank" :width="`${$f * 1000}px`" @close="showBank = false" @submit="confirmBank">
      <el-table ref="multipleTable" size="mini" :data="bankList" tooltip-effect="dark" class="wp100">
        <el-table-column label="开户行" show-overflow-tooltip prop="bank" :min-width="`${150 * $f}`" />
        <el-table-column label="银行卡号" show-overflow-tooltip prop="address" :min-width="`${150 * $f}`" />
        <el-table-column label="操作" :width="`${100 * $f}`" align="center">
          <template slot-scope="{ row }">
            <img v-if="row.selected === false" class="public_singImg" src="@/assets/img/orderManagement/unchecked_icon.png" @click="selectedBank(row)" />
            <img v-else class="public_singImg" src="@/assets/img/orderManagement/checked_icon.png" />
          </template>
        </el-table-column>
        <template slot="empty">
          <PageEmptyData />
        </template>
      </el-table>
    </PageDialog>
  </div>
</template>
<script>
import DataOverview from './components/DataOverview.vue';
import ContentCountAnalysis from './components/ContentCountAnalysis.vue';
import SaleTrend from './components/SaleTrend.vue';
import tableFun from '@/mixin/tableFun.js';
import exportFun from '@/mixin/exportFun.js';
import dayjs from 'dayjs'; // ES 2015
export default {
  components: { SaleTrend, DataOverview, ContentCountAnalysis },
  mixins: [tableFun, exportFun],
  data() {
    return {
      saleTrendDateRange: [], //回款额趋势数据
      saleTrendData: {}, //回款额趋势数据
      saleTrendDataHasZero: false, //回款额趋势数据是是否全部是0
      saleTrendType: '1',
      salesCountTrendDateRange: [], //回款量趋势数据
      salesCountTrendData: {}, //回款额趋势数据
      salesCountTrendDataHasZero: false, //回款额趋势数据是否全部是0
      saleCountTrendType: '1',
      addReceiveDialogVisible: false, //是否回款
      purchaseInvoiceReceiveList: [
        { value: '1', label: '已回款' },
        { value: '2', label: '未回款' }
      ],
      addInputTicketDialogVisible: false, //进项票
      purchaseInvoiceList: [
        { value: '1', label: '已进项票' },
        { value: '2', label: '未进项票' }
      ],
      bankRadio: 1,
      isShowFilter: false, //是否显示高级搜索
      orderDialogVisible: false, //新增订单弹窗
      addParams: {},
      params: {},
      // ====== 上传文件的参数 start ======
      importDialogVisible: false, //导入弹窗
      fileList: [], //导入的文件
      uploadFileUrl: '', //上传文件接口路径
      // ====== 上传文件的参数 end ======
      orderParams: { commonSearch: '', total: 0, pageSize: 200, pageNum: 1 }, //订单参数
      deleteDialogVisible: false, //删除弹窗
      exporttDialogVisible: false, //导出弹窗
      // 表单验证规则
      ticketRules: {
        invoiceNo: [
          { required: true, message: '请输入发票号', trigger: 'blur' },
          { pattern: /^[0-9]{20}$/, message: '发票号必须为20位数字', trigger: ['blur', 'change'] }
        ]
      },
      receiveRules: {
        purchaseInvoiceReceive: [{ required: true, message: '请选择是否回款', trigger: 'change' }]
      },
      inputTicketRules: {
        purchaseInvoice: [{ required: true, message: '请选择进项票', trigger: 'change' }]
      }
    };
  },
  computed: {
    headers() {
      return {
        token: window.localStorage.getItem('token')
      };
    }
  },
  created() {
    this.getOrderDataList(); //获取订单列表
    this.initData(); //初始化数据
  },
  methods: {
    //初始化数据
    initData() {
      const today = dayjs().format('YYYY-MM-DD');
      const sevenDaysAgo = dayjs()
        .subtract(30, 'day')
        .format('YYYY-MM-DD');
      this.saleTrendDateRange = [sevenDaysAgo, today];
      this.salesCountTrendDateRange = [sevenDaysAgo, today];
      this.changeSaleTrend(this.saleTrendDateRange, '1'); //回款额趋势
      this.changeSalesCountTrend(this.salesCountTrendDateRange, '1'); //回款量趋势
    },
    getDateRange(startDate, endDate, format, unit) {
      const dates = [];
      if (unit === 'day') {
        let current = dayjs(startDate);
        const end = dayjs(endDate);
        while (current.isBefore(end) || current.isSame(end)) {
          dates.push(current.format(format));
          current = current.add(1, unit);
        }
      } else if (unit === 'Month') {
        let current = dayjs(startDate + '-01', 'YYYY-MM-DD');
        const end = dayjs(endDate + '-01', 'YYYY-MM-DD');
        while (current.isBefore(end) || current.isSame(end, 'month')) {
          dates.push(current.format('YYYY-MM'));
          current = current.add(1, 'month');
        }
      } else {
        let current = startDate;
        const end = endDate;
        while (current < end) {
          dates.push(current);
          current = current + 1;
        }
      }
      return dates;
    },
    //选择维度（日、月、季度、年）
    filterDimension(type, name) {
      if (type === '1') {
        const today = dayjs().format('YYYY-MM-DD');
        const last = dayjs()
          .subtract(30, 'day')
          .format('YYYY-MM-DD');
        this[name] = [last, today];
      } else if (type === '2') {
        const today = dayjs().format('YYYY-MM');
        const last = dayjs()
          .subtract(12, 'month')
          .format('YYYY-MM');
        this[name] = [last, today];
      } else {
        const today = dayjs().format('YYYY');
        const last = dayjs()
          .subtract(1, 'year')
          .format('YYYY');
        this[name] = [last, today];
      }
    },
    //回款额趋势
    async changeSaleTrend(time, type) {
      let params = {};
      let timeFormate;
      let timeType;
      if (type === '1') {
        params = { startDate: dayjs(time[0]).format('YYYY-MM-DD'), endDate: dayjs(time[1]).format('YYYY-MM-DD') };
        timeFormate = 'YYYY-MM-DD';
        timeType = 'day';
      } else if (type === '2') {
        params = { startMonth: dayjs(time[0]).format('YYYY-MM'), endMonth: dayjs(time[1]).format('YYYY-MM') };
        timeFormate = 'YYYY-MM';
        timeType = 'Month';
      } else {
        params = { starYear: dayjs(time[0]).format('YYYY'), endYear: dayjs(time[1]).format('YYYY') };
        timeFormate = 'YYYY';
        timeType = 'Year';
      }
      let res = await this.$api.post(this.$url.statisticsReceivedAmountTrend, params);
      if (res.code == 200) {
        let times = this.getDateRange(params[`start${type === '1' ? 'Date' : timeType}`], params[`end${type === '1' ? 'Date' : timeType}`], timeFormate, timeType);
        let xData = [];
        let sData = [];
        times.forEach(el => {
          let idx = res.data.findIndex(son => el === son.date);
          xData.push(el);
          if (idx === -1) {
            sData.push(0);
          } else {
            sData.push(res.data[idx].data);
          }
        });
        this.saleTrendDataHasZero = sData.every(el => el === 0);
        this.saleTrendData = { xData, sData };
      }
    },
    //回款量趋势
    async changeSalesCountTrend(time, type) {
      let params = {};
      let timeFormate;
      let timeType;
      if (type === '1') {
        params = { startDate: dayjs(time[0]).format('YYYY-MM-DD'), endDate: dayjs(time[1]).format('YYYY-MM-DD') };
        timeFormate = 'YYYY-MM-DD';
        timeType = 'day';
      } else if (type === '2') {
        params = { startMonth: dayjs(time[0]).format('YYYY-MM'), endMonth: dayjs(time[1]).format('YYYY-MM') };
        timeFormate = 'YYYY-MM';
        timeType = 'Month';
      } else {
        params = { starYear: dayjs(time[0]).format('YYYY'), endYear: dayjs(time[1]).format('YYYY') };
        timeFormate = 'YYYY';
        timeType = 'Year';
      }
      let res = await this.$api.post(this.$url.statisticsReceivedQtyTrend, params);
      if (res.code == 200) {
        let times = this.getDateRange(params[`start${type === '1' ? 'Date' : timeType}`], params[`end${type === '1' ? 'Date' : timeType}`], timeFormate, timeType);
        let xData = [];
        let sData = [];
        times.forEach(el => {
          let idx = res.data.findIndex(son => el === son.date);
          xData.push(el);
          if (idx === -1) {
            sData.push(0);
          } else {
            sData.push(res.data[idx].data);
          }
        });
        this.salesCountTrendDataHasZero = sData.every(el => el === 0);
        this.salesCountTrendData = { xData, sData };
      }
    },
    //关闭弹窗
    closeDialog() {
      this.addInputTicketDialogVisible = false;
      this.addReceiveDialogVisible = false;
      this.deleteDialogVisible = false;
      this.exporttDialogVisible = false;
      this.orderDialogVisible = false;
      this.importDialogVisible = false;
      this.addDialogVisible = false;
      this.addParams = Object.assign({}, this.$options.data().addParams); //重置参数
    },
    //标记发票号需要相同的公司
    markInvoiceNo(val) {
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('请先选择');
      }
      const firstCompanyId = this.multipleSelection[0].companyId;
      const allSameCompany = this.multipleSelection.every(item => item.companyId === firstCompanyId);
      if (!allSameCompany) {
        this.$message.warning('请选择相同公司的订单');
        return;
      }
      this.batchUpdateBtn(val);
    },
    // ====== 上传文件的方法 start ======
    //上传文件成功
    uploadFileSucess() {},
    //删除文件时出发此方法
    handleRemoveFile(file, fileList) {
      this.fileList = fileList;
    },
    //文件状态改变触发此方法
    changeUploadFile(file, fileList) {
      this.fileList = fileList;
    },
    //确认上传文件
    confirmUpload() {
      if (this.fileList.length == 0) {
        this.$message.warning('请上传文件');
      } else {
        this.$refs.upload.submit(); //上传文件
      }
    },
    // ====== 上传文件的方法 edn ======
    //搜索
    filterCommit() {
      this.orderParams = {
        ...this.orderParams,
        pageSize: 10,
        pageNum: 1
      };
      this.getOrderDataList();
    },
    //获取订单列表
    async getOrderDataList() {
      let res = await this.$api.get(this.$url.saleOrderList, this.orderParams);
      this.tableData = res.rows;
      this.orderParams.total = res.total;
    },
    //批量操作
    batchUpdateBtn(dialog) {
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('请先选择');
      }
      this.showDilogBtn(dialog);
    },
    //确认标记发票
    async confirmTicket() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (Object.keys(this.addParams).length > 0 && this.multipleSelection.length === 0) {
            this.addParams.saleOrderIds = [this.addParams.id];
            let res = await this.$api.post(this.$url.saleOrderUpdate, this.addParams);
            if (res.code === 200) {
              this.$message.success('发票号更新成功');
              this.closeDialog();
              this.filterCommit();
            }
          } else {
            let axiosList = [];
            this.multipleSelection.forEach(async item => {
              item.invoiceNo = this.addParams.invoiceNo;
              item.saleOrderIds = [item.id];
              await axiosList.push(this.$api.post(this.$url.saleOrderUpdate, item));
            });
            Promise.all(axiosList).then(() => {
              this.$message.success('发票号更新成功');
              this.filterCommit();
              this.closeDialog();
            });
          }
        }
      });
    },
    //确认标记回款
    async confirmMark() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          let axiosList = [];
          this.multipleSelection.forEach(async item => {
            item.purchaseInvoiceReceive = this.addParams.purchaseInvoiceReceive;
            item.saleOrderIds = [item.id];
            await axiosList.push(this.$api.post(this.$url.saleOrderUpdate, item));
          });
          Promise.all(axiosList).then(() => {
            this.$message.success('回款状态更新成功');
            window.location.reload();
          });
        }
      });
    },
    //标记进项票
    inputTicketBtn(item) {
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('请先选择');
      }
      this.addParams = Object.assign({}, item);
      this.showDilogBtn('addInputTicketDialogVisible');
    },
    async confirmInputTicket() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          let axiosList = [];
          this.multipleSelection.forEach(async item => {
            item.purchaseInvoice = this.addParams.purchaseInvoice;
            item.saleOrderIds = [item.id];
            await axiosList.push(this.$api.post(this.$url.saleOrderUpdate, item));
          });
          Promise.all(axiosList).then(() => {
            this.$message.success('进项票更新成功');
            window.location.reload();
          });
        }
      });
    },
    //修改页码
    orderChangePage(pageNum) {
      this.orderParams.pageNum = pageNum;
      this.getOrderDataList();
    },
    //修改每页显示的条数
    orderChangeSize(size) {
      this.orderParams.pageSize = size;
      this.orderParams.pageNum = 1;
      this.getOrderDataList();
    },
    // 获取公司审核状态
    async checkCompanyAuditStatus(companyId) {
      try {
        let res = await this.$api.get(this.$url.companyAll);
        // 假设返回的第一个公司就是当前操作的公司
        if (res.data && res.data.length > 0) {
          let company = res.data.find(item => item.id === companyId);
          if (company) {
            return company.isComplete;
          }
        }
        return '2'; // 默认未审核
      } catch (error) {
        console.error('获取公司审核状态失败:', error);
        return '2'; // 出错时默认未审核
      }
    },
    //导出excel - 重写方法，添加公司审核状态验证
    async exportListBtn(val) {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请先选择');
        return;
      }
      //导出开票单需要相同的公司
      if (val === 'exportInvoiceBtnClick') {
        const firstCompanyId = this.multipleSelection[0].companyId;
        const allSameCompany = this.multipleSelection.every(item => item.companyId === firstCompanyId);
        if (!allSameCompany) {
          this.$message.warning('请选择相同公司的订单');
          return;
        }
      }
      // 检查公司审核状态
      const isComplete = await this.checkCompanyAuditStatus(this.multipleSelection[0].companyId);
      if (isComplete === '2') {
        this.$message.warning('请先去公司列表完善该公司信息');
        return;
      }
      this[val]();
    }
  }
};
</script>
<style lang="less" scoped>
.pub_select1 {
  width: 80px;
}
.tableBox {
  min-height: calc(100% - 80px);
}
.echarts_parent {
  width: 100%;
  overflow: hidden;
  .echarts {
    background: #ffffff;
    border-radius: 16px 16px 16px 16px;
    padding: 20px;
    box-sizing: border-box;
  }
  .echarts {
    float: left;
    & + .echarts {
      margin-left: 16px;
    }
    .echarts_header {
      font-size: 16px;
      color: #0a0b0d;
    }
  }
  .table_content {
    width: 100%;
  }
  .table_filter_search {
    width: 200px;
  }
  .table_filter_select {
    width: 150px;
  }
  .high_filter_btn {
    width: 108px;
  }
}
.addOrder {
  .el-form-item {
    float: left;
    width: 309px;
    margin-bottom: 10px;
    &.search_btn {
      width: auto;
    }
  }
  ::v-deep .pub_date_picker.el-date-editor.el-input {
    width: 229px;
  }
}
</style>
